<?php

namespace library;

use think\facade\Cache;

class WaveCache
{
    public $redisCache;
    public $lockPrefix = 'jq:';

    public function __construct()
    {
        $this->redisCache = Cache::store('redis');
    }

    public function waveGet($key, callable $callback, $timeout)
    {
        //查看redis是否有数据
        $save_key = $this->lockPrefix . $key;
        $redisResult = $this->redisCache->get($save_key);
        //redis没数据,存储数据
        if (!$redisResult) {
            return $this->waveSet($save_key, $callback, $timeout);
        }

        return $redisResult;
    }

    public function waveSet($key, callable $callback, $timeout)
    {
        //数据库读取
        try {
            $result = call_user_func($callback);
        } catch (\Exception $e) {
            throw new OWException('读取数据异常', $e->getMessage());
        }

        //更新redis缓存
        $this->redisCache->set($key, $result, $timeout);
        return $result;
    }
}